package com.z.redis.command.impl.zset;

import com.z.redis.RedisCore;
import com.z.redis.command.CommandType;
import com.z.redis.command.WriteCommand;
import com.z.redis.datatype.BytesWrapper;
import com.z.redis.datatype.RedisData;
import com.z.redis.datatype.RedisZset;
import com.z.redis.resp.BulkString;
import com.z.redis.resp.Resp;
import com.z.redis.resp.RespInt;
import io.netty.channel.ChannelHandlerContext;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * zrem key member1 [member2…]
 * 移除有序集合中一个/多个成员
 */
public class Zrem implements WriteCommand {
    private BytesWrapper key;
    private List<BytesWrapper> members;

    @Override
    public CommandType type(){
        return CommandType.zrem;
    }

    public void setContent(Resp[] array){
        key = ((BulkString) array[1]).getContent();
        members = Stream.of(array)
                .skip(2)
                .map(member -> ((BulkString) member).getContent())
                .collect(Collectors.toList());
    }

    @Override
    public void handle(ChannelHandlerContext ctx, RedisCore redisCore){
        RedisData redisData = redisCore.get(key);
        if(redisData == null){
            ctx.writeAndFlush(BulkString.NullBulkString);
        }else if(redisData instanceof RedisZset){
            int remove = ((RedisZset) redisData).remove(members);
            ctx.writeAndFlush(new RespInt(remove));
        }else{
            throw new UnsupportedOperationException("type not Zset");
        }
    }

    @Override
    public void handle(RedisCore redisCore){
        RedisData redisData = redisCore.get(key);
        if(redisData instanceof RedisZset){
            ((RedisZset) redisData).remove(members);
        }
    }
}
